package persistence

import (
	"context"
	"zxstudy.com/domain/entity"
	"zxstudy.com/infrastructure/ent"
	"zxstudy.com/infrastructure/ent/car"
)

type Cars struct {
	client	*ent.Client
}

func NewCarRepository(client *ent.Client) *Cars {
	return &Cars{
		client: client,
	}
}

func (cars *Cars) Create(ctx context.Context, c *entity.Car) (*entity.Car, error) {
	cc := cars.client.Car.
		Create().
		SetModel(c.Model).
		SetRegisterdAt(c.RegisteredAt)
	if c.Owner != nil {
		cc.SetOwnerID(c.Owner.ID)
	}
	
	newCar, err := cc.Save(ctx)
	if err != nil {
		return nil, err
	}
	
	return newCar.ToDomain(), nil
}

func (cars *Cars) Delete(ctx context.Context, c *entity.Car) error {
	err := cars.client.Car.
		DeleteOneID(c.ID).
		Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

func (cars *Cars) Get(ctx context.Context, id int) (*entity.Car, error) {
	newCar, err := cars.client.Car.
		Query().
		Where(car.ID(id)).
		WithOwner().
		Only(ctx)
	if err != nil {
		return nil, err
	}
	
	return newCar.ToDomain(), nil
}

func (cars *Cars) Cars(ctx context.Context) ([]*entity.Car, error) {
	list, err := cars.client.Car.
		Query().
		WithOwner().
		All(ctx)
	if err != nil {
		return nil, err
	}

	newList := make([]*entity.Car, 0, len(list))
	for _, c := range list {
		newList = append(newList, c.ToDomain())
	}
	
	return newList, nil
}